package com.habdqn.easybuy.web.manage.news;

import com.habdqn.easybuy.entity.News;
import com.habdqn.easybuy.entity.User;
import com.habdqn.easybuy.service.NewsService;
import com.habdqn.easybuy.service.UserService;
import com.habdqn.easybuy.service.impl.NewsServiceImpl;
import com.habdqn.easybuy.service.impl.UserServiceImpl;
import com.habdqn.easybuy.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Xing.Jiejian
 * @date 2020/11/28
 */
@WebServlet(name = "NewsUpdateServlet", urlPatterns = "/manage/news/update")
public class UpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String strId = request.getParameter("id");
        if (StringUtils.isNotBlank(strId)) {
            int id = Integer.parseInt(strId);
            // 先获取原用户信息
            NewsService newsService = new NewsServiceImpl();
            News news = newsService.queryById(id);
            // 更新表单数据
            news.setTitle(request.getParameter("title"));
            news.setContent(request.getParameter("content"));

            // 执行更新业务
            if (newsService.update(news) != null) {
                response.setContentType("text/html;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.println("<script>");
                out.println("alert('修改新闻成功！');");
                out.println("location.href='" + request.getContextPath() + "/manage/news';");
                out.println("</script>");
            } else {
                request.setAttribute("errorMsg", "修改失败");
                request.setAttribute("news", news);
                request.getRequestDispatcher("/WEB-INF/manage/news/news-modify.jsp").forward(request, response);
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String strId = request.getParameter("id");
        if (StringUtils.isNotBlank(strId)) {
            int id = Integer.parseInt(strId);
            // 先获取原用户信息
            NewsService newsService = new NewsServiceImpl();
            News news = newsService.queryById(id);
            request.setAttribute("news", news);
            request.getRequestDispatcher("/WEB-INF/manage/news/news-modify.jsp").forward(request, response);
        } else {
            // 未传入id则直接进入列表页
            response.sendRedirect(request.getContextPath() + "/manage/news");
        }
    }
}
